﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using POSPlus.EZBarTender.SignsPrinting;
using POSPlus.MvcPassiveView;
using POSPlus.DatabaseOperations;
using POSPlus.EZBarTender.DatabaseOperations;
using POSPlus.PrintManager;
using Util;

namespace POSPlus.EZBarTender.SignsPrinting
{
	public delegate void CommitChangesEventHandler(object sender, EventArgs e);
	public delegate void NextSignEventHandler(object sender, EventArgs e);
	public delegate void PreviousSignEventHandler(Object sender, EventArgs e);
	public delegate void JobAddedEventHandler(object sender, EventArgs e);
	public delegate void PrintButtonEventHandler(Object sender, EventArgs e);

	public partial class SignsEditor : Form, ISignsPrintingView
	{
		#region Member
		private ChangeRequestEvents _changeRequestedEvents;
//		private PrintManagerModel _printManagerModel;
		private Sign _currentSign;
		private String _batchNo;
        private ApplicationConfig appConfig;
		#endregion

		#region Properties
		public event CommitChangesEventHandler CommitChanges;
		public event NextSignEventHandler GetNextSign;
		public event PreviousSignEventHandler GetPreviousSign;
		public event JobAddedEventHandler JobAdded;
		public event PrintButtonEventHandler PrintButtonPressed; 

		public String CorpConnectionString { get; private set; }
		public String LocalConnectionString { get; private set; }
		public string Upc
		{
			get { return _upcTextBox.Text; }
			set { _upcTextBox.Text = value; }
		}
		public string Description1
		{
			get { return _desc1TextBox.Text; }
			set { _desc1TextBox.Text = value; }
		}
		public string Description2
		{
			get { return _desc2TextBox.Text; }
			set { _desc2TextBox.Text = value; }
		}
		public String Description3
		{
			get { return _desc3TextBox.Text; }
			set { _desc3TextBox.Text = value; }
		}
		public string Description4
		{
			get { return _desc4TextBox.Text; }
			set {
				if (_desc4TextBox.InvokeRequired)
				{

				}
				else
					_desc4TextBox.Text = value; 
			
			}
		}
		public string Description5
		{
			get { return _desc5TextBox.Text; }
			set { _desc5TextBox.Text = value; }
		}
		public string JobName
		{
			get { return textBoxJobName.Text; }
			set { textBoxJobName.Text = value; }
		}
		public double NormalPrice
		{
			get { return Convert.ToDouble(_normal_PriceTextBox.Text); }
			set { _normal_PriceTextBox.Text = value.ToString(); }
		}
		public double PriceUom
		{
			get { return Convert.ToDouble(_price_UomTextBox.Text); }
			set { _price_UomTextBox.Text = value.ToString(); }
		}
		public string Selling
		{
			get { return _sellingTextBox.Text; }
			set { _sellingTextBox.Text = value; }
		}
		public string ProductSize
		{
			get { return _sizeTextBox.Text; }
			set { _sizeTextBox.Text = value; }
		}
		public DateTime WeekEnding
		{
			get { return _weekEndingDatePicker.Value; }
			set { _weekEndingDatePicker.Value = value; }
		}
		public double YouSave
		{
			get { return Convert.ToDouble(_youSaveTextBox.Text); }
			set { _youSaveTextBox.Text = value.ToString(); }
		}
		public String SignType
		{
			get { return _signTypeComboBox.Text; }
			set { _signTypeComboBox.Text = value; }
		}
		public String SignSize
		{
			get { return _signSizeComboBox.Text; }
			set { _signSizeComboBox.Text = value; }
		}
		public Sign CurrentSign
		{
			get { return _currentSign; }
			set { _currentSign = value; }
		}
		public Int32 DuplicateCount
		{
			get { return Convert.ToInt32(_duplicateCount.Value); }
			set 
			{
				_duplicateCount.Value = value; 
			}
		}
		public String BatchNo {
			get
			{
				return _batchNo;
			}
			set
			{
				_batchNo = value;
			}
		}
        public DateTime StartDate
        {
            get{ return _startDatePicker.Value; }
            set { _startDatePicker.Value = value; }

        }
		#endregion

		#region Constructors

		public SignsEditor(String corpConnectionString, String localConnectionString, ApplicationConfig appConfig)
		{
			InitializeComponent();
			CorpConnectionString = corpConnectionString;
			LocalConnectionString = localConnectionString;
			_changeRequestedEvents = new ChangeRequestEvents(this);

            this.appConfig = appConfig;
            if(!appConfig.EnableElston)
                DisableElston();
		}
/*
		public SignsEditor(String corpConnectionString, String localConnectionString, PrintManagerModel model)
		{
			InitializeComponent();
			CorpConnectionString = corpConnectionString;
			LocalConnectionString = localConnectionString;
			_changeRequestedEvents = new ChangeRequestEvents(this);
			_printManagerModel = model;
		}
 */
		#endregion

		#region Methods
		private void SignsProto_LoadBetter(Object sender, EventArgs e)
		{

		}

		public void RegisterChangeRequestListener<T>(string propertyName, EventHandler<PropertyChangeRequestEventArgs<T>> handler)
		{
			_changeRequestedEvents.RegisterListener<T>(propertyName, handler);
		}
		public void UnRegisterChangeRequestListener<T>(string propertyName, EventHandler<PropertyChangeRequestEventArgs<T>> handler)
		{
			_changeRequestedEvents.UnRegisterListener<T>(propertyName, handler);
		}

		private void NextSign()
		{
			OnNextSign(EventArgs.Empty);
		}

		private void OnNextSign(EventArgs e)
		{
			if (GetNextSign != null)
				GetNextSign(this, e);
		}

		private void CommitChange()
		{
			OnCommitChanges(EventArgs.Empty);			
		}

		protected void OnCommitChanges(EventArgs e)
		{
			if (CommitChanges != null)
				CommitChanges(this, e);
		}

		private void AddJob()
		{
			OnJobAdded(EventArgs.Empty);
		}

		private void OnJobAdded(EventArgs e)
		{
			if (JobAdded != null)
				JobAdded(this, e);
		}

		private void OnPrintButtonPressed(EventArgs e)
		{
			if (PrintButtonPressed != null)
				PrintButtonPressed(this, e);
		}

		private void _nextButton_Click(object sender, EventArgs e)
		{
			CurrentSign.IsNew = false;
			CommitChange();
			NextSign();
		}

		#region PrintManager

		private void _addToPrintManagerButton_Click(object sender, EventArgs e)
		{
			_changeRequestedEvents.Fire<string>("JobName", textBoxJobName.Text);
			Upc = "";
			_upcTextBox.Focus();
			if (CurrentSign != null)
				CurrentSign.IsNew = false;
            if (_signTypeComboBox.Text == "Smart Buy")
                _changeRequestedEvents.Fire<string>("BatchNo", "Smart Buy");
			CommitChange();
			AddJob();
			_changeRequestedEvents.Fire<string>("BatchNo", "");
		}

		private void _duplicateCount_ValueChanged(object sender, EventArgs e)
		{
			_changeRequestedEvents.Fire<Int32>("DuplicateCount", (int)_duplicateCount.Value);
		}

		private void _signSizeComboBox_SelectedIndexChanged(object sender, EventArgs e)
		{
			_changeRequestedEvents.Fire<String>("SignSize", _signSizeComboBox.Text);

			textBoxJobName.Text = _signTypeComboBox.Text + _signSizeComboBox.Text;

			if (CanAdd())
			{
				_addToPrintManagerButton.Enabled = true;
			}
			else
				_addToPrintManagerButton.Enabled = false;
		}

		private void _signTypeComboBox_SelectedIndexChanged(object sender, EventArgs e)
		{
			_changeRequestedEvents.Fire <String>("SignType", _signTypeComboBox.Text);
			textBoxJobName.Text = _signTypeComboBox.Text + _signSizeComboBox.Text;
			if (CanAdd())
				_addToPrintManagerButton.Enabled = true;
			else
				_addToPrintManagerButton.Enabled = false;

		}
		#endregion
		#endregion

		private bool CanAdd()
		{
			return (_signSizeComboBox.Text.Length > 0 &&
				_signTypeComboBox.Text.Length > 0 &&
				EdlpInfo.UpcExists(_upcTextBox.Text, LocalConnectionString) == 1 &&
				_sellingTextBox.Text.Length > 0 &&
				textBoxJobName.Text.Length > 0);
		}

		private void textBoxJobName_Validated(object sender, EventArgs e)
		{
			_changeRequestedEvents.Fire<string>("JobName", textBoxJobName.Text);
		}

		private void _upcTextBox_Validated(object sender, EventArgs e)
		{
			while (_upcTextBox.Text.Length < 13)
				_upcTextBox.Text = "0" + _upcTextBox.Text;
			_changeRequestedEvents.Fire<String>("Upc", _upcTextBox.Text);

			if (CanAdd())
				_addToPrintManagerButton.Enabled = true;
			else
				_addToPrintManagerButton.Enabled = false;

			List<ProductBatch> productBatch = ProductBatch.GetAllByUpc(LocalConnectionString, Upc);
			List<ProductBatchesHeader> header = new List<ProductBatchesHeader>();
			foreach (ProductBatch batch in productBatch)
			{
				header.AddRange(ProductBatchesHeader.GetAllByBatchNo(LocalConnectionString, batch.BatchNo));
			}

            if (header.Count > 0)
            {
                BatchSelectionDialog dialog = new BatchSelectionDialog(header);
                DialogResult result = dialog.ShowDialog();

                if (result == DialogResult.OK)
                {
                    _changeRequestedEvents.Fire<String>("BatchNo", dialog.BatchNo);
                }
                else if (EdlpInfo.GetEdlpStatus(_upcTextBox.Text, LocalConnectionString) == 1)
                {
                    _changeRequestedEvents.Fire<String>("Selling", _normal_PriceTextBox.Text);
                }
                else
                {
                    _changeRequestedEvents.Fire<String>("BatchNo", "No Batch");
                }
            }
            else
            {
                _changeRequestedEvents.Fire<String>("BatchNo", "No Batch");
            }
		}
		
		private void _desc1TextBox_Validated(object sender, EventArgs e)
		{
			_changeRequestedEvents.Fire<String>("Description1", _desc1TextBox.Text);
		}
		private void _desc2TextBox_Validated(object sender, EventArgs e)
		{
			_changeRequestedEvents.Fire<String>("Description2", _desc2TextBox.Text);
		}
		private void _desc3TextBox_Validated(Object sender, EventArgs e)
		{
			_changeRequestedEvents.Fire<String>("Description3", _desc3TextBox.Text);
		}

		private void _normal_PriceTextBox_Validated(object sender, EventArgs e)
		{
			_normal_PriceTextBox.Text = ConvertPriceText(_normal_PriceTextBox.Text);
			_changeRequestedEvents.Fire<Double>("NormalPrice", Convert.ToDouble(_normal_PriceTextBox.Text));
		}

		private void _sellingTextBox_Validated(object sender, EventArgs e)
		{
			_sellingTextBox.Text = ConvertPriceText(_sellingTextBox.Text);
			_changeRequestedEvents.Fire<String>("Selling", _sellingTextBox.Text);
		}
		private void _desc4TextBox_Validated(object sender, EventArgs e)
		{
			_changeRequestedEvents.Fire<String>("Description4", _desc4TextBox.Text);
		}
		private void _desc5TextBox_Validated(object sender, EventArgs e)
		{
			_changeRequestedEvents.Fire<String>("Description5", _desc5TextBox.Text);
		}
		private void _price_UomTextBox_Validated(object sender, EventArgs e)
		{
            try
            {
                _changeRequestedEvents.Fire<Double>("PriceUom", Convert.ToDouble(_price_UomTextBox.Text));
            }
            catch (Exception ex) { }

		}
		private void _sizeTextBox_Validated(object sender, EventArgs e)
		{
			_changeRequestedEvents.Fire<String>("Size", _sizeTextBox.Text);
		}
		private void _weekEndingDatePicker_ValueChanged(object sender, EventArgs e)
		{
			_changeRequestedEvents.Fire<DateTime>("WeekEnding", _weekEndingDatePicker.Value);
		}
        private void _startDatePicker_ValueChanged(object sender, EventArgs e)
        {
            _changeRequestedEvents.Fire<DateTime>("StartDate", _startDatePicker.Value);
        }
		private void _youSaveTextBox_Validated(object sender, EventArgs e)
		{
			_changeRequestedEvents.Fire<Double>("YouSave", Convert.ToDouble(_youSaveTextBox.Text));
		}

		private void _printButton_Click(object sender, EventArgs e)
		{
			OnPrintButtonPressed(e);
			NextSign();
		}

		private void _previousButton_Click(object sender, EventArgs e)
		{
			if (GetPreviousSign != null)
				GetPreviousSign(this, e);
		}

		private string ConvertPriceText(string p)
		{
            String price = p;
            String quanity = "";

            if (p.Contains("/"))
            {
                quanity = p.Split('/')[0];
                price = p.Split('/')[1];
            }

            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < price.Length; i++)
                if (char.IsDigit(price[i]) || price[i] == '/' || price[i] == '.')
                    sb.Append(price[i]);

            price = sb.ToString();

            if (price.Contains("."))
            {
                String[] dollarsAndCents = price.Split('.');

                if (dollarsAndCents.Length < 2)
                    price = price + "00";
                else if (dollarsAndCents[1].Length < 2)
                {
                    for (int i = 0; i < 2 - dollarsAndCents[1].Length; i++)
                        price += "0";
                }
                else
                    for (int i = 0; i < dollarsAndCents[1].Length - 2; i++)
                        price = price.Substring(0, price.Length - 1);
            }
            else
            {
                if (price.Length == 1)
                    price = "0.0" + price;
                else if (price.Length == 2)
                    price = "0." + price;
                else
                    price = price.Insert(price.Length - 2, ".");
            }
            if (quanity.Length > 0)
                return quanity + "/" + price;
            else
                return price;
		}

		private void General_KeyDown(object sender, KeyEventArgs e)
		{
			if (e.KeyCode == Keys.Enter)
				SendKeys.Send("{TAB}");
		}

		private void textBoxJobName_TextChanged(object sender, EventArgs e)
		{
			if (CanAdd())
			{
				_addToPrintManagerButton.Enabled = true;
			}
			else
			{
				_addToPrintManagerButton.Enabled = false;
			}
		}

        private void DisableElston()
        {
            _youSaveTextBox.Enabled = false;
            _sizeTextBox.Enabled = false;
            _price_UomTextBox.Enabled = false;
        }
	}
}